<template>
  <div style="height: 97vh; display: flex; align-items: center; justify-content: center; overflow: hidden; ">
    <div style="flex: 1">
      <img src="../../../assets/login.png" width="100%">
    </div>
    <div style="flex: 1; display: flex; align-items: center; justify-content: center;">
      <el-form :model="user" :rules="rules" ref="LoginRef">
        <div style="font-size: 25px; font-weight: bold; text-align: center; margin-bottom: 20px">
          欢迎登录迷你商城系统
        </div>
        <el-form-item prop="name">
          <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入用户名" v-model="user.name"
                    style="width: 300px;">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" size="medium" placeholder="请输入密码" v-model="user.password"
                    style="width: 300px;" show-password>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <div style="display: flex">
            <el-input prefix-icon="el-icon-circle-check" size="medium" placeholder="请输入验证码" v-model="user.code"
                      style="flex: 1; width: 150px"></el-input>
            <div style="flex: 1; height: 36px">
              <valid-code @update:value="getCode"></valid-code>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%; background-color: #0f9876; color: white;" @click="login"
                     @keyup.enter="keyDown">登录
          </el-button>
        </el-form-item>
        <div style="display: flex;margin-top: -8px;">
          <div style="flex: 1;">还没有账号？请 <span style="color: #0f9876;cursor: pointer;"
                                                    @click="$router.push(`/register`)">注册</span>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import ValidCode from "@/components/ValidCode";
import request from "@/utils/request";

export default {
  name: "LoginView.vue",
  components: {ValidCode},

  data() {
    //自定义验证码校验
    const validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'));
      } else if (value.toLowerCase() !== this.code.toLowerCase()) {
        callback(new Error('验证码错误'));
      } else {
        callback();
      }
    };
    return {
      //用户信息
      user: {
        name: "",
        password: "",
        code: ""      //用户输入的验证码
      },
      code: "",        //验证码组件生成的验证码
      //表单校验规则
      rules: {
        name: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        code: [
          {validator: validateCode, trigger: 'blur'}
        ],
      },
    }
  },

  methods: {
    getCode(code) {
      console.log(code)
      this.code = code
    },

    //回车触发登录
    keyDown(e) {
      if (e.keyCode === 13) {
        this.login();
      }
    },

    //登录方法
    login() {
      //校验表单是否通过，通过则发送请求
      this.$refs['LoginRef'].validate(valid => {
        //校验通过
        if (valid) {
          //封装数据对象
          const user = {
            name: this.user.name,
            password: this.user.password
          }
          //发送请求
          request.post('/user/admin/login', user).then(res => {
            console.log(res);
            if (res.data.code === 200) {
              this.$message.success('登录成功')
              //存储用户数据
              localStorage.setItem('user', JSON.stringify(res.data))
              //区分登录者是管理员还是用户后进行跳转
              if (res.data.data.status === 1) {
                this.$router.push('/adminView')
              } else {
                this.$router.push('/clientView')
              }
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }
      })
    }

  },

  mounted() {
    //绑定事件
    window.addEventListener('keydown', this.keyDown);
  },
  //销毁事件
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  }

}
</script>

<style>
body {
  margin: 0;
}
</style>